<?php

namespace common\behaviors;

use common\models\sys\Modelhistory;
use common\queues\HistoryJob;
use Yii;
use yii\base\Behavior;
use yii\db\ActiveRecord;

class ActiveRecordHistoryBehavior extends Behavior
{
    public function events()
    {
        return [
            ActiveRecord::EVENT_AFTER_UPDATE => 'saveOpLog',
            ActiveRecord::EVENT_AFTER_INSERT => 'saveOpLog',
            ActiveRecord::EVENT_AFTER_DELETE => 'saveOpLog',
        ];
    }

    public function saveOpLog($event)
    {
        if ($this->owner->hasErrors()) {
            return;
        }

        $model = new ModelHistory();
        $user_id = Yii::$app->user->id ?? 0;
        if ($user_id == 0) {
//            $user_id = $this->owner->user_id ?? 0;
            $user_id = $this->owner->log_user_id ?? 0;
        }
        $model->user_id = $user_id;

        //表名
        $model->op_table_name = $this->owner->getTableSchema()->fullName;

        //主键
        $primaryKey = [];
        foreach ($this->owner->primaryKey() as $key) {
            $primaryKey[] = $this->owner->$key;
        }
        $model->primary_key = implode(',', $primaryKey);

        //唯一标识
        $model->unique = '';
        if ($this->owner->hasAttribute('order_no')) {
            $model->unique = $this->owner->order_no;
        } elseif ($this->owner->hasAttribute('sku')) {
            $model->unique = $this->owner->sku;
        } else if ($this->owner->hasAttribute('spu')) {
            $model->unique = $this->owner->spu;
        }

        if ($event->name == ActiveRecord::EVENT_AFTER_INSERT) {
            //新增
            $model->op_type = 'INSERT';
            $model->new_value = $this->owner->getAttributes();
        } else if ($event->name == ActiveRecord::EVENT_AFTER_UPDATE) {
            //更新
            $model->op_type = 'UPDATE';
            $changedAttributes = $event->changedAttributes;
            if(isset($changedAttributes['created_at'])) unset($changedAttributes['created_at']);
            if(isset($changedAttributes['updated_at'])) unset($changedAttributes['updated_at']);
            if (empty($changedAttributes)) return;//无更新字段
//
            $old_value = []; $new_value = [];//临时保存修改数据array
            foreach ($changedAttributes as $updatedFieldKey => $updatedFieldValue) {
                if($updatedFieldValue != $this->owner->$updatedFieldKey){//旧数据 对比 新数据
                    $old_value[$updatedFieldKey] = $updatedFieldValue;//旧数据
                    $new_value[$updatedFieldKey] = $this->owner->$updatedFieldKey;//新数据
                }
            }

            if(empty($old_value) && empty($new_value)) return;//无更新字段
            $model->old_value = $old_value;
            $model->new_value = $new_value;


        } else if ($event->name == ActiveRecord::EVENT_AFTER_DELETE) {
            //删除
            $model->op_type = 'DELETE';
            $model->old_value = $this->owner->getAttributes();
        }

 

        if(!in_array(Yii::$app->id,['app-console'])){
            $model->op_modules = Yii::$app->controller->module->id??'';
        }else{
            $model->op_modules = Yii::$app->controller->id??'';
        }

        $model->os_type = $this->owner->log_os_type ?? Yii::$app->id;
//        $model->os_type = Yii::$app->id??'other';
        $model->created_at = date('Y-m-d H:i:s');
        // $queueId = Yii::$app->queueLogs->push(new HistoryJob([
        //     'data' => serialize($model),
        // ]));
//        $model->save(false);
    }
}
